package com.qm.console.service.analysis;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.qm.console.component.exception.BusinessException;
import com.qm.console.component.util.DateUtil;
import com.qm.console.component.util.GetPropertiesUtils;
import com.qm.console.component.util.HttpInvokeUtil;
import com.qm.console.component.util.TimeUtils;
import com.qm.console.controller.dto.BaseRsp;
import com.qm.console.controller.dto.ResultEnum;
import com.qm.console.dao.dm.AccountRegisterStatisticsMapper;
import com.qm.console.dao.dm.AdvisorSummaryDataMapper;
import com.qm.console.dao.dm.MarketStatisticsMapper;
import com.qm.console.dao.dm.OrderSummaryDataMapper;
import com.qm.console.dao.mapper.*;
import com.qm.console.dao.model.*;
import com.qm.console.model.ProductProcessDOExample;
import com.qm.console.pubdef.constant.UrlConstant;
import com.qm.console.pubdef.dto.analysis.*;
import com.qm.console.pubdef.dto.anchor.AnchorVerifyAdminDTO;
import com.qm.console.pubdef.dto.anchor.ImMsgQueryDTO;
import com.qm.console.pubdef.dto.anchor.ScreenShotQueryDTO;
import com.qm.console.pubdef.dto.anchor.TurnSignUpDTO;
import com.qm.console.pubdef.dto.bx.BxDisplayFieldDTO;
import com.qm.console.pubdef.dto.user.PageInfoDTO;
import com.qm.console.pubdef.dto.user.VideoVoiceListDTO;
import com.qm.console.pubdef.dto.analysis.ChannelQueryDTO;

import com.qm.console.pubdef.dto.analysis.PropQueryDTO;
import com.qm.console.pubdef.dto.analysis.liftingRecordDTO;
import com.qm.console.pubdef.dto.analysis.onlineQueryDTO;
import com.qm.console.service.jw.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;

/**
 * //                       _oo0oo_
 * //                      o8888888o
 * //                      88" . "88
 * //                      (| -_- |)
 * //                      0\  =  /0
 * //                    ___/`---'\___
 * //                  .' \\|     |// '.
 * //                 / \\|||  :  |||// \
 * //                / _||||| -:- |||||- \
 * //               |   | \\\  -  /// |   |
 * //               | \_|  ''\---/''  |_/ |
 * //               \  .-\__  '-'  ___/-. /
 * //             ___'. .'  /--.--\  `. .'___
 * //          ."" '<  `.___\_<|>_/___.' >' "".
 * //         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 * //         \  \ `_.   \_ __\ /__ _/   .-` /  /
 * //     =====`-.____`.___ \_____/___.-`___.-'=====
 * //                       `=---='
 * //
 * //
 * //     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * //
 * //               佛祖保佑         永无BUG
 * <p>
 * com.qm.console.service.analysis
 * Created on 2020/7/7.
 */
@Service
@Slf4j
public class AnalysisService {

    private static final Long BASE_DIAMOND = Long.parseLong(GetPropertiesUtils.getProperty("common", "base_diamond"));
    private static final Long BASE_POINT = Long.parseLong(GetPropertiesUtils.getProperty("common", "base_point"));

    public static Map<String, String> ipAddressMap = new HashMap<>();

    @Autowired
    private BasicStatisticsDOMapper basicStatisticsDOMapper;
    @Autowired
    private overviewStatisticsDOMapper overviewStatisticsDOMapper;
    @Autowired
    private QuickMatchStatisticsDOMapper quickMatchStatisticsDOMapper;
    @Autowired
    private ActivateStatisticsDOMapper activateStatisticsDOMapper;
    @Autowired
    private ChatStatisticsDOMapper chatStatisticsDOMapper;
    @Autowired
    private DivisionStatisticsDOMapper divisionStatisticsDOMapper;
    @Autowired
    private RechargeStatisticsDOMapper rechargeStatisticsDOMapper;
    @Autowired
    private UserProfitStatisticsDOMapper userProfitStatisticsDOMapper;
    @Autowired
    private WithdrawStatisticsDOMapper withdrawStatisticsDOMapper;
    @Autowired
    private ManualRechargeDOMapper manualRechargeDOMapper;
    @Autowired
    private DiamondStatisticsDOMapper diamondStatisticsDOMapper;
    @Autowired
    private LiftingRecordStatisticsDOMapper liftingRecordStatisticsDOMapper;
    @Autowired
    private UserClassifyDOMapper userClassifyDOMapper;
    @Autowired
    private DateUtil dateUtil;
    @Autowired
    private LossRetainedStatisticsDOMapper lossRetainedStatisticsDOMapper;
    @Autowired
    private AccountRegisterDOMapper accountRegisterDOMapper;
    @Autowired
    private AbnormityWarningDOMapper abnormityWarningDOMapper;
    @Autowired
    private ImMsgDOMapper imMsgDOMapper;
    @Autowired
    private OnlineAccountDOMapper onlineAccountDOMapper;
    @Autowired
    private ChatRecordDOMapper chatRecordDOMapper;
    @Autowired
    private ScreenShotsDOMapper screenShotsDOMapper;
    @Autowired
    private TurnLotteryStatisticsDOMapper turnLotteryStatisticsDOMapper;
    @Autowired
    private TurnSignUpStatisticsDOMapper turnSignUpStatisticsDOMapper;
    @Autowired
    private EggRecordDOMapper eggRecordDOMapper;
    @Autowired
    private NewEggSingleStatisticsDOMapper newEggSingleStatisticsDOMapper;
    @Autowired
    private RechargeAnalysisDOMapper rechargeAnalysisDOMapper;
    @Autowired
    private PromotionCostsDOMapper promotionCostsDOMapper;
    @Autowired
    private AccountRegisterStatisticsMapper accountRegisterStatisticsMapper;
    @Autowired
    private MarketStatisticsMapper marketStatisticsMapper;
    @Autowired
    private AdvisorSummaryDataMapper advisorSummaryDataMapper;
    @Autowired
    private OrderSummaryDataMapper orderSummaryDataMapper;

    public List<ChatRecordDO> realTimeList(VideoVoiceListDTO query){
        List<ChatRecordDO> chatRecordList= chatRecordDOMapper.realTimeList(query);

        chatRecordList.forEach(item -> {
            ScreenShotQueryDTO screenQuery = new ScreenShotQueryDTO();
            String channelId = item.getChannelId();
            if (channelId == null){
                return;
            }
            String tableId = channelId.substring(channelId.length() - 1, channelId.length());
            screenQuery.setChannelId(channelId);
            screenQuery.setTableId(tableId);
            List<ScreenShotsDO> screenData = screenShotsDOMapper.selectMaxRate(screenQuery);
            screenData.forEach(screenItem -> {
                int uid = screenItem.getUid();
                if (uid == item.getFromUser()){
                    item.setFromRate(screenItem.getRate());
                    item.setFromUrl(screenItem.getUrl());
                }
                if (uid == item.getToUser()){
                    item.setToRate(screenItem.getRate());
                    item.setToUrl(screenItem.getUrl());
                }
            });
        });
        return chatRecordList;
    }

    public List<ChatRecordDO> realTimeHistory(VideoVoiceListDTO query){
        return chatRecordDOMapper.realTimeHistory(query);
    }

    public List<EggRecordDO> getEggRecords(EggQueryDTO query){
        return eggRecordDOMapper.list(query);
    }

    public List<NewEggSingleStatisticsDO> eggSingle(EggQueryDTO query){
        return newEggSingleStatisticsDOMapper.list(query);
    }

    public List<EggRecordDO> getEggStatistics(EggQueryDTO query){
        return eggRecordDOMapper.statisticsList(query);
    }

    public List<EggRecordDO> getEggAnalysisList(EggQueryDTO query){
        return eggRecordDOMapper.AnalysisList(query);
    }

    public Integer getEggRecordsCount(EggQueryDTO query){
        return eggRecordDOMapper.count(query);
    }

    public Integer getEggStatisticsCount(EggQueryDTO query){
        return eggRecordDOMapper.statisticsCount(query);
    }

    public Integer getEggAnalysisCount(EggQueryDTO query){
        return eggRecordDOMapper.AnalysisCount(query);
    }

    public int userRechargeCount(ChannelQueryDTO query) {
        return rechargeStatisticsDOMapper.userRechargeCount(query);
    }

    public int PromotionCostsCount(ChannelQueryDTO query) {
        return promotionCostsDOMapper.count(query);
    }

    public List<PromotionCostsDO> PromotionCostsList(ChannelQueryDTO query) {
        return promotionCostsDOMapper.list(query);
    }

    public List<RechargeStatisticsDO> userRecharges(ChannelQueryDTO query) {
        return rechargeStatisticsDOMapper.userRechargeList(query);
    }

    public BaseRsp getTurnLottery(TurnSignUpDTO query){
        if (query.getOffset() == null || query.getLimit() == null) {
            throw new BusinessException(ResultEnum.PARA_ERR);
        }
        Date startTime;
        Date endTime;
        Date minTime = new Date(2021 - 1900, Calendar.MARCH, 1);
        Date maxTime = new Date();
        if (query.getStartTime() == null) {
            startTime = minTime;
        } else {
            startTime = TimeUtils.parse(query.getStartTime(), TimeUtils.DATE_FORMAT_DATE_D);
            if (startTime.getTime() < minTime.getTime()) {
                startTime = minTime;
            }
        }
        if (query.getEndTime() == null) {
            endTime = maxTime;
        } else {
            endTime = TimeUtils.parse(query.getEndTime(), TimeUtils.DATE_FORMAT_DATE_D);
            if (endTime.getTime() > maxTime.getTime()) {
                endTime = maxTime;
            }
        }
        Calendar startTimeC = Calendar.getInstance();
        startTimeC.setTime(startTime);
        Calendar endTimeC = Calendar.getInstance();
        endTimeC.setTime(endTime);
        List<String> months = dateUtil.listMonths(startTimeC, endTimeC);

        List<String> tables = months.stream().map(month -> "turn_sign_up_statistics_" + month).collect(Collectors.toList());
        query.setTables(tables);
        if (tables.isEmpty()) {
            return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("list", Collections.emptyList(), "count", 0));
        }
        List<TableCountDO> counts = turnLotteryStatisticsDOMapper.count(query);
        Collections.reverse(counts);

        final List<String> contentTables = new ArrayList<>();
        int totalCount = 0;
        int realOffset = 0;
        boolean started = false;
        for (TableCountDO count : counts) {
            if (query.getOffset() >= totalCount && query.getOffset() < totalCount + count.getTotal()) {
                //临界条件..
                contentTables.add(count.getTableName());
                realOffset = query.getOffset() - totalCount;
                started = true;
            } else if (started && query.getOffset() + query.getLimit() >= totalCount) {
                contentTables.add(count.getTableName());
            }
            totalCount += count.getTotal();
        }
        if (contentTables.isEmpty()) {
            return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("list", Collections.emptyList(), "count", 0));
        }
        query.setOffset(realOffset);
        query.setTables(contentTables);

        List<TurnLotteryStatisticsDO> list = turnLotteryStatisticsDOMapper.list(query);
        return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of(
                "list", list, "count", totalCount
        ));
    }

    public BaseRsp statisticsList(TurnSignUpDTO query){
        if (query.getOffset() == null || query.getLimit() == null) {
            throw new BusinessException(ResultEnum.PARA_ERR);
        }
        Date startTime;
        Date endTime;
        Date minTime = new Date(2021 - 1900, Calendar.MARCH, 1);
        Date maxTime = new Date();
        if (query.getStartTime() == null) {
            startTime = minTime;
        } else {
            startTime = TimeUtils.parse(query.getStartTime(), TimeUtils.DATE_FORMAT_DATE_D);
            if (startTime.getTime() < minTime.getTime()) {
                startTime = minTime;
            }
        }
        if (query.getEndTime() == null) {
            endTime = maxTime;
        } else {
            endTime = TimeUtils.parse(query.getEndTime(), TimeUtils.DATE_FORMAT_DATE_D);
            if (endTime.getTime() > maxTime.getTime()) {
                endTime = maxTime;
            }
        }
        Calendar startTimeC = Calendar.getInstance();
        startTimeC.setTime(startTime);
        Calendar endTimeC = Calendar.getInstance();
        endTimeC.setTime(endTime);
        List<String> months = dateUtil.listMonths(startTimeC, endTimeC);

        List<String> tables = months.stream().map(month -> "turn_sign_up_statistics_" + month).collect(Collectors.toList());
        query.setTables(tables);
        if (tables.isEmpty()) {
            return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("list", Collections.emptyList(), "count", 0));
        }
        List<TableCountDO> counts = turnLotteryStatisticsDOMapper.statisticsCount(query);
        Collections.reverse(counts);

        final List<String> contentTables = new ArrayList<>();
        int totalCount = 0;
        int realOffset = 0;
        boolean started = false;
        for (TableCountDO count : counts) {
            if (query.getOffset() >= totalCount && query.getOffset() < totalCount + count.getTotal()) {
                //临界条件..
                contentTables.add(count.getTableName());
                realOffset = query.getOffset() - totalCount;
                started = true;
            } else if (started && query.getOffset() + query.getLimit() >= totalCount) {
                contentTables.add(count.getTableName());
            }
            totalCount += count.getTotal();
        }
        if (contentTables.isEmpty()) {
            return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("list", Collections.emptyList(), "count", 0));
        }
        query.setOffset(realOffset);
        query.setTables(contentTables);

        List<TurnLotteryStatisticsDO> list = turnLotteryStatisticsDOMapper.statisticsList(query);
        return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of(
                "list", list, "count", totalCount
        ));
    }

    public List<TurnSignUpStatisticsDO> getApplyItem(TurnSignUpDTO paramMap){
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(paramMap.getDatetime());
        calendar.getWeekYear();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        String format = month >= 9 ? "turn_sign_up_statistics_%s_%d" : "turn_sign_up_statistics_%s_0%d";
        String result = String.format(format, year, month + 1);
        paramMap.setTableName(result);
        return turnSignUpStatisticsDOMapper.applyList(paramMap);
    }

    public List<TurnSignUpStatisticsDO> getRedPacketItem(TurnSignUpDTO paramMap){
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(paramMap.getDatetime());
        calendar.getWeekYear();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        String format = month >= 9 ? "turn_sign_up_statistics_%s_%d" : "turn_sign_up_statistics_%s_0%d";
        String result = String.format(format, year, month + 1);
        paramMap.setTableName(result);
        return turnSignUpStatisticsDOMapper.rebPacketList(paramMap);
    }

    public BaseRsp getTurnRedPacket(TurnSignUpDTO query){
        if (query.getOffset() == null || query.getLimit() == null) {
            throw new BusinessException(ResultEnum.PARA_ERR);
        }
        Date startTime;
        Date endTime;
        Date minTime = new Date(2021 - 1900, Calendar.MARCH, 1);
        Date maxTime = new Date();
        if (query.getStartTime() == null) {
            startTime = minTime;
        } else {
            startTime = TimeUtils.parse(query.getStartTime(), TimeUtils.DATE_FORMAT_DATE_D);
            if (startTime.getTime() < minTime.getTime()) {
                startTime = minTime;
            }
        }
        if (query.getEndTime() == null) {
            endTime = maxTime;
        } else {
            endTime = TimeUtils.parse(query.getEndTime(), TimeUtils.DATE_FORMAT_DATE_D);
            if (endTime.getTime() > maxTime.getTime()) {
                endTime = maxTime;
            }
        }
        Calendar startTimeC = Calendar.getInstance();
        startTimeC.setTime(startTime);
        Calendar endTimeC = Calendar.getInstance();
        endTimeC.setTime(endTime);
        List<String> months = dateUtil.listMonths(startTimeC, endTimeC);

        List<String> tables = months.stream().map(month -> "turn_sign_up_statistics_" + month).collect(Collectors.toList());
        query.setTables(tables);
        if (tables.isEmpty()) {
            return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("list", Collections.emptyList(), "count", 0));
        }
        List<TableCountDO> counts = turnLotteryStatisticsDOMapper.redPacketCount(query);
        Collections.reverse(counts);

        final List<String> contentTables = new ArrayList<>();
        int totalCount = 0;
        int realOffset = 0;
        boolean started = false;
        for (TableCountDO count : counts) {
            if (query.getOffset() >= totalCount && query.getOffset() < totalCount + count.getTotal()) {
                //临界条件..
                contentTables.add(count.getTableName());
                realOffset = query.getOffset() - totalCount;
                started = true;
            } else if (started && query.getOffset() + query.getLimit() >= totalCount) {
                contentTables.add(count.getTableName());
            }
            totalCount += count.getTotal();
        }
        if (contentTables.isEmpty()) {
            return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of("list", Collections.emptyList(), "count", 0));
        }
        query.setOffset(realOffset);
        query.setTables(contentTables);

        List<TurnLotteryStatisticsDO> list = turnLotteryStatisticsDOMapper.redPacketList(query);
        return new BaseRsp(ResultEnum.SUCCESS, ImmutableMap.of(
                "list", list, "count", totalCount
        ));
    }

    public List<OnlineAccountDO> onlineUser(onlineQueryDTO query){
        return onlineAccountDOMapper.onlineUser(query);
    }

    public int onlineUserCount(onlineQueryDTO query){
        return onlineAccountDOMapper.onlineUserCount(query);
    }

    public List<OnlineAccountDO> onlineHistory(onlineQueryDTO query){
        return onlineAccountDOMapper.onlineHistory(query);
    }

    public List<ImMsgDO> liveChat(ImMsgQueryDTO query){
        return imMsgDOMapper.liveChat(query);
    }

    public int liveChatCount(ImMsgQueryDTO query){
        return imMsgDOMapper.liveChatCount(query);
    }

    public List<ImMsgDO> liveChatDetail(ImMsgQueryDTO query){
        return imMsgDOMapper.liveChatDetail(query);
    }

    public int liveChatDetailCount(ImMsgQueryDTO query){
        return imMsgDOMapper.liveChatDetailCount(query);
    }

    public List<AbnormityWarningDO> getAbnormityWarning(ChannelQueryDTO query){
        return abnormityWarningDOMapper.list(query);
    }

    public Integer AbnormityWarningCount(ChannelQueryDTO query){
        return abnormityWarningDOMapper.count(query);
    }

    public int basicCount(ChannelQueryDTO query) {
        return basicStatisticsDOMapper.count(query);
    }

    public List<BasicStatisticsDO> basics(ChannelQueryDTO query) {
        List<BasicStatisticsDO> result = basicStatisticsDOMapper.list(query);
        result.stream().forEach(item -> {
            if (dateUtil.isAfterNDaysBefore(item.getTargetDate(), 0)) {
                item.setRemain1Day(null);
            }
        });
        return result;
    }

    public int overviewCount(ChannelQueryDTO query) {
        return overviewStatisticsDOMapper.count(query);
    }

    public List<quickMatchStatisticsDO> quickMatchList(ChannelQueryDTO query) {
        return quickMatchStatisticsDOMapper.list(query);
    }

    public int quickMatchCount(ChannelQueryDTO query) {
        return quickMatchStatisticsDOMapper.count(query);
    }

    public List<overviewStatisticsDO> overview(ChannelQueryDTO query) {
        List<overviewStatisticsDO> result = overviewStatisticsDOMapper.list(query);
        result.stream().forEach(item -> {
            if (dateUtil.isAfterNDaysBefore(item.getTargetDate(), 0)) {
                item.setRemain1Day(null);
            }
        });
        return result;
    }

    public List<String> overvieTests(){
        return overviewStatisticsDOMapper.getAbTests();
    }

    public List<LiftingRecordStatisticsDO> liftingRecordList(liftingRecordDTO query){
        return liftingRecordStatisticsDOMapper.list(query);
    }

    public int liftingRecordCount(liftingRecordDTO query){
        return liftingRecordStatisticsDOMapper.count(query);
    }

    public List<LossRetainedStatisticsDO> activeUserList(LossRetainedDTO query){
        return lossRetainedStatisticsDOMapper.list(query);
    }

    public int activeUserCount(LossRetainedDTO query){
        return lossRetainedStatisticsDOMapper.count(query);
    }

    public List<LossRetainedStatisticsDO> WashAwayList(LossRetainedDTO query){
        return lossRetainedStatisticsDOMapper.washAwayList(query);
    }

    public int WashAwayCount(LossRetainedDTO query){
        return lossRetainedStatisticsDOMapper.washAwayCount(query);
    }

    public List<String> getlossRetainedTests(){
        return lossRetainedStatisticsDOMapper.getAbTests();
    }

    public int activateCount(ChannelQueryDTO query) {
        return activateStatisticsDOMapper.count(query);
    }

    public List<ActivateStatisticsDO> activates(ChannelQueryDTO query) {
        List<ActivateStatisticsDO> result = activateStatisticsDOMapper.list(query);
        return result;
    }

    public int chatCount(ChannelQueryDTO query) {
        return chatStatisticsDOMapper.count(query);
    }

    public List<ChatStatisticsDO> chats(ChannelQueryDTO query) {
        return chatStatisticsDOMapper.list(query);
    }

    public int divisionCount(ChannelQueryDTO query) {
        return divisionStatisticsDOMapper.count(query);
    }

    public List<DivisionStatisticsDO> divisions(ChannelQueryDTO query) {
        return divisionStatisticsDOMapper.list(query);

    }

    public int rechargeCount(ChannelQueryDTO query) {
        return rechargeStatisticsDOMapper.count(query);
    }

    public List<RechargeAnalysisDO> rechargeAnalysisList(ChannelQueryDTO query) {
        return rechargeAnalysisDOMapper.list(query);
    }

    public int rechargeAnalysisCount(ChannelQueryDTO query) {
        return rechargeAnalysisDOMapper.count(query);
    }

    public List<RechargeStatisticsDO> recharges(ChannelQueryDTO query) {
        List<RechargeStatisticsDO> result = rechargeStatisticsDOMapper.list(query);
        PropQueryDTO params = new PropQueryDTO();
        if (query.getAppChannel() != null) {
            params.setChannels(Arrays.asList(query.getAppChannel()));
        }
        params.setOffset(query.getOffset());
        params.setLimit(query.getLimit());
        List<DiamondPropDO> active = diamondPropDOMapper.listActive(params);
        for(DiamondPropDO tmp: active){
            for(RechargeStatisticsDO ob: result) {
                if (tmp.getTargetDate().toString().equals(ob.getTargetDate().toString())){
                    ob.setActivateCount(Integer.parseInt(tmp.getActivateCount().toString()));
                    ob.setActiveCount(Integer.parseInt(tmp.getActiveCount().toString()));
                    break;
                }
            }
        }
        if (result.size() > 0 && StringUtils.isEmpty(query.getAppChannel())) { // 有选择渠道的话，分渠道数据不叠加手动+入的部分
            Date max = result.get(0).getTargetDate();
            List<ManualRechargeDO> list = manualRechargeDOMapper.list(TimeUtils.formatDate(max));
            // accumulate
            for (int i = 1; i < list.size(); i++) {
                list.get(i).setAmount(list.get(i - 1).getAmount() + list.get(i).getAmount());
            }
            Collections.reverse(list);
            result.forEach(item -> {
                for (ManualRechargeDO manualRechargeDO : list) {
                    if (manualRechargeDO.getTargetDate().equals(item.getTargetDate()) || manualRechargeDO.getTargetDate().before(item.getTargetDate())) {
                        item.setTotalDiamond(item.getTotalDiamond() + manualRechargeDO.getAmount());
                        break;
                    }
                }
            });
        }
        return result;

    }

    public int userProfitCount(ChannelQueryDTO query) {
        return userProfitStatisticsDOMapper.count(query);
    }

    public List<UserProfitStatisticsDO> userProfits(ChannelQueryDTO query) {
        return userProfitStatisticsDOMapper.list(query);
    }

    public int withdrawCount(ChannelQueryDTO query) {
        return withdrawStatisticsDOMapper.count(query);
    }

    public List<WithdrawStatisticsDO> withdraws(ChannelQueryDTO query) {
        List<WithdrawStatisticsDO> result = withdrawStatisticsDOMapper.list(query);
        result.forEach(item -> {
            item.setTotalPoint(item.getTotalPoint() + BASE_POINT);
        });
        return result;
    }

    public List<Map<String, String>> getChannels() {
        List<ActivateStatisticsDO> temp = activateStatisticsDOMapper.getChannels();
        List<Map<String, String>> result = new ArrayList<>();
        temp.forEach(ActivateStatisticsDO -> {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("key", ActivateStatisticsDO.getAppChannel());
            paramMap.put("label", ActivateStatisticsDO.getAppChannel());
            result.add(paramMap);
        });
        return result;
    }

    public List<Map<String, String>> getVersions() {
        List<ActivateStatisticsDO> temp = activateStatisticsDOMapper.getVersions();
        List<Map<String, String>> result = new ArrayList<>();
        temp.forEach(ActivateStatisticsDO -> {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("key", ActivateStatisticsDO.getAppVersion());
            paramMap.put("label", ActivateStatisticsDO.getAppVersion());
            result.add(paramMap);
        });
        return result;
    }

    public List<Map<String, String>> getAppNames() {
        List<ActivateStatisticsDO> temp = activateStatisticsDOMapper.getAppName();
        List<Map<String, String>> result = new ArrayList<>();
        temp.forEach(ActivateStatisticsDO -> {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("key", ActivateStatisticsDO.getAppName());
            paramMap.put("label", ActivateStatisticsDO.getAppName());
            result.add(paramMap);
        });
        return result;
    }

    public List<DiamondStatisticsDO> diamondStatistics(ChannelQueryDTO query) {
        List<DiamondStatisticsDO> result = diamondStatisticsDOMapper.list(query);
        if (result.size() > 0 && StringUtils.isEmpty(query.getAppChannel())) { // 有选择渠道的话，分渠道数据不叠加手动+入的部分
            Date max = result.get(0).getTargetDate();
            List<ManualRechargeDO> list = manualRechargeDOMapper.list(TimeUtils.formatDate(max));
            // accumulate
            for (int i = 1; i < list.size(); i++) {
                list.get(i).setAmount(list.get(i - 1).getAmount() + list.get(i).getAmount());
            }
            Collections.reverse(list);
            result.forEach(item -> {
                for (ManualRechargeDO manualRechargeDO : list) {
                    if (manualRechargeDO.getTargetDate().equals(item.getTargetDate()) || manualRechargeDO.getTargetDate().before(item.getTargetDate())) {
                        item.setTotalDiamond(item.getTotalDiamond() + manualRechargeDO.getAmount());
                        break;
                    } else if (manualRechargeDO.getTargetDate().equals(item.getTargetDate())) {
                        item.setReplenishment(item.getReplenishment() + manualRechargeDO.getAmount());
                    }
                }
            });
        }
        return result;
    }

    public int diamondStatisticsCount(ChannelQueryDTO query) {
        return diamondStatisticsDOMapper.count(query);
    }

    /*
    道具产销
     */
    @Autowired
    private DiamondPropDOMapper diamondPropDOMapper;
    @Autowired
    private ScorePropDOMapper scorePropDOMapper;
    @Autowired
    private CardPropDOMapper cardPropDOMapper;
    @Autowired
    private TicketPropDOMapper ticketPropDOMapper;
    @Autowired
    private VoiceCardPropDOMapper voiceCardPropDOMapper;

    public int diamondTotal(PropQueryDTO query) {
        return diamondPropDOMapper.total(query);
    }

    public int scoreTotal(PropQueryDTO query) {
        return scorePropDOMapper.total(query);
    }

    public int cardTotal(PropQueryDTO query) {
        return cardPropDOMapper.total(query);
    }

    public int ticketTotal(PropQueryDTO query) {
        return ticketPropDOMapper.total(query);
    }

    public int voiceCardTotal(PropQueryDTO query) {
        return voiceCardPropDOMapper.total(query);
    }

    public List<DiamondPropDO> diamondList(PropQueryDTO query) {
        List<DiamondPropDO> result = diamondPropDOMapper.list(query);
        List<DiamondPropDO> active = diamondPropDOMapper.listActive(query);
        for(DiamondPropDO tmp: active){
            for(DiamondPropDO ob: result) {
                if (tmp.getTargetDate().toString().equals(ob.getTargetDate().toString())){
                    ob.setActivateCount(tmp.getActivateCount());
                    ob.setActiveCount(tmp.getActiveCount());
                    break;
                }
            }
        }
        if (result.size() > 0 && query.getChannels() == null) { // 有选择渠道的话，分渠道数据不叠加手动+入的部分
            Date max = result.get(0).getTargetDate();
            List<ManualRechargeDO> list = manualRechargeDOMapper.list(TimeUtils.formatDate(max));
            if (list.size()>0){
                // accumulate
                for (int i = 1; i < list.size(); i++) {
                    list.get(i).setAmount(list.get(i - 1).getAmount() + list.get(i).getAmount());
                }
                Collections.reverse(list);
                result.forEach(item -> {
                    for (ManualRechargeDO manualRechargeDO : list) {
                        if (manualRechargeDO.getTargetDate().equals(item.getTargetDate()) || manualRechargeDO.getTargetDate().before(item.getTargetDate())) {
                            item.setDiamondInventory(item.getDiamondInventory() + manualRechargeDO.getAmount());
                            item.setDiamondInventory30days(item.getDiamondInventory30days() + manualRechargeDO.getAmount());
                            break;
                        } else if (manualRechargeDO.getTargetDate().equals(item.getTargetDate())) {
                            item.setDiamondChange(item.getDiamondChange() + manualRechargeDO.getAmount());
                        }
                    }

                });
            }
        }
        System.out.println(result);
        return result;
    }

    public List<String> getDiamondAbTests(){
        return diamondPropDOMapper.getAbTests();
    }

    public List<ScorePropDO> scoreList(PropQueryDTO query) {
        List<ScorePropDO> result = scorePropDOMapper.list(query);
//        for(int i=0; i<result.size(); i++){
//            ScorePropDO item = result.get(i);
//            item.setScoreInventory(item.getScoreInventory());
//            item.setScoreChange(item.getScoreChange());
//            item.setScoreInventory30days(item.getScoreInventory30days());
//        }
        List<DiamondPropDO> active = diamondPropDOMapper.listActive(query);
        for(DiamondPropDO tmp: active){
            for(ScorePropDO ob: result) {
                if (tmp.getTargetDate().toString().equals(ob.getTargetDate().toString())){
                    ob.setActivateCount(tmp.getActivateCount());
                    ob.setActiveCount(tmp.getActiveCount());
                    break;
                }
            }
        }
        return result;
    }

    public List<String> getScoreAbTests(){
        return scorePropDOMapper.getAbTests();
    }

    public List<CardPropDO> cardList(PropQueryDTO query) {
        List<CardPropDO> result = cardPropDOMapper.list(query);
        List<DiamondPropDO> active = diamondPropDOMapper.listActive(query);
        for(DiamondPropDO tmp: active){
            for(CardPropDO ob: result) {
                if (tmp.getTargetDate().toString().equals(ob.getTargetDate().toString())){
                    ob.setActivateCount(tmp.getActivateCount());
                    ob.setActiveCount(tmp.getActiveCount());
                    break;
                }
            }
        }
        return result;
    }

    public List<String> getCardAbTests(){
        return cardPropDOMapper.getAbTests();
    }

    public List<TicketPropDO> ticketList(PropQueryDTO query) {
        List<TicketPropDO> result = ticketPropDOMapper.list(query);
        List<DiamondPropDO> active = diamondPropDOMapper.listActive(query);
        for(DiamondPropDO tmp: active){
            for(TicketPropDO ob: result) {
                if (tmp.getTargetDate().toString().equals(ob.getTargetDate().toString())){
                    ob.setActivateCount(tmp.getActivateCount());
                    ob.setActiveCount(tmp.getActiveCount());
                    break;
                }
            }
        }
        return result;
    }

    public List<String> getTicketAbTests(){
        return ticketPropDOMapper.getAbTests();
    }

    public List<VoiceCardPropDO> voiceCardList(PropQueryDTO query) {
        List<VoiceCardPropDO> result = voiceCardPropDOMapper.list(query);
        List<DiamondPropDO> active = diamondPropDOMapper.listActive(query);
        for(DiamondPropDO tmp: active){
            for(VoiceCardPropDO ob: result) {
                if (tmp.getTargetDate().toString().equals(ob.getTargetDate().toString())){
                    ob.setActivateCount(tmp.getActivateCount());
                    ob.setActiveCount(tmp.getActiveCount());
                    break;
                }
            }
        }
        return result;
    }

    public List<String> getVoiceCardAbTests(){
        return voiceCardPropDOMapper.getAbTests();
    }

    public List<Map> diamondInventoryList(PropQueryDTO query) {

        Date current_date = new Date();
        List<Map> ret = generate_30_days(current_date, "inventory");
        String inventoryDate = TimeUtils.addDay(current_date, -15, "yyyy-MM-dd");
        query.setInventoryDate(inventoryDate);

        List<Map> result = diamondPropDOMapper.inventoryList(query);
        if (result.size() > 0 && query.getChannels() == null) { // 有选择渠道的话，分渠道数据不叠加手动+入的部分
            Date max = (Date) result.get(0).get("target_date");
            List<ManualRechargeDO> list = manualRechargeDOMapper.list(TimeUtils.formatDate(max));
            // accumulate
            for (int i = 1; i < list.size(); i++) {
                list.get(i).setAmount(list.get(i - 1).getAmount() + list.get(i).getAmount());
            }
            Collections.reverse(list);
            for(int i=0; i<result.size(); i++) {
                Map item = result.get(i);
                for (ManualRechargeDO manualRechargeDO : list) {
                    if (manualRechargeDO.getTargetDate().equals(item.get("target_date")) || manualRechargeDO.getTargetDate().before((Date)item.get("target_date"))) {
                        item.put("inventory", (Integer.parseInt(item.get("inventory").toString()) + manualRechargeDO.getAmount()));
                        break;
                    }
                }
            };
        }
        result.forEach(item->{
            for(int i=0; i<ret.size(); i++){
                if(item.get("target_date").toString().equals(ret.get(i).get("target_date").toString())){
                    ret.get(i).put("inventory", item.getOrDefault("inventory", 0));
                }
            }
        });
        return ret;
    }

    public List<Map> cardInventoryList(PropQueryDTO query) {

        Date current_date = new Date();
        List<Map> ret = generate_30_days(current_date, "inventory");
        String inventoryDate = TimeUtils.addDay(current_date, -15, "yyyy-MM-dd");
        query.setInventoryDate(inventoryDate);
        List<Map> result = cardPropDOMapper.inventoryList(query);
        result.forEach(item->{
            for(int i=0; i<ret.size(); i++){
                if(item.get("target_date").toString().equals(ret.get(i).get("target_date").toString())){
                    ret.get(i).put("inventory", item.getOrDefault("inventory", 0));
                }
            }
        });
        return ret;
    }

    public List<Map> ticketInventoryList(PropQueryDTO query) {

        Date current_date = new Date();
        List<Map> ret = generate_30_days(current_date, "inventory");
        String inventoryDate = TimeUtils.addDay(current_date, -15, "yyyy-MM-dd");
        query.setInventoryDate(inventoryDate);
        List<Map> result = ticketPropDOMapper.inventoryList(query);
        result.forEach(item->{
            for(int i=0; i<ret.size(); i++){
                if(item.get("target_date").toString().equals(ret.get(i).get("target_date").toString())){
                    ret.get(i).put("inventory", item.getOrDefault("inventory", 0));
                }
            }
        });
        return ret;
    }

    public List<Map> scoreInventoryList(PropQueryDTO query) {

        Date current_date = new Date();
        List<Map> ret = generate_30_days(current_date, "inventory");
        String inventoryDate = TimeUtils.addDay(current_date, -15, "yyyy-MM-dd");
        query.setInventoryDate(inventoryDate);
        List<Map> result = scorePropDOMapper.inventoryList(query);
        result.forEach(item->{
            for(int i=0; i<ret.size(); i++){
                if(item.get("target_date").toString().equals(ret.get(i).get("target_date").toString())){
                    ret.get(i).put("inventory", item.getOrDefault("inventory", 0));
                }
            }
        });
        return ret;
    }

    public List<Map> voiceCardInventoryList(PropQueryDTO query) {
        Date current_date = new Date();
        List<Map> ret = generate_30_days(current_date, "inventory");
        String inventoryDate = TimeUtils.addDay(current_date, -15, "yyyy-MM-dd");
        query.setInventoryDate(inventoryDate);
        List<Map> result = voiceCardPropDOMapper.inventoryList(query);
        result.forEach(item->{
            for(int i=0; i<ret.size(); i++){
                if(item.get("target_date").toString().equals(ret.get(i).get("target_date").toString())){
                    ret.get(i).put("inventory", item.getOrDefault("inventory", 0));
                }
            }
        });
        return ret;
    }

    public List<Map> diamondActiveList(PropQueryDTO query) {
        Date current_date = new Date();
        String activeDate = TimeUtils.addDay(current_date, -30, "yyyy-MM-dd");
        query.setActiveDate(activeDate);
        List<Map> result = diamondPropDOMapper.activeList(query);
        List<Map> ret = generate_30_days(current_date, "active");

        try{
            if (result.size() > 0 && query.getChannels() == null) { // 有选择渠道的话，分渠道数据不叠加手动+入的部分
                Date max = (Date) result.get(0).get("target_date");
                List<ManualRechargeDO> list = manualRechargeDOMapper.list(TimeUtils.formatDate(max));
                if (list.size()>0) {
                    // accumulate
                    for (int i = 1; i < list.size(); i++) {
                        list.get(i).setAmount(list.get(i - 1).getAmount() + list.get(i).getAmount());
                    }
                    Collections.reverse(list);
                    result.forEach(item -> {
                        for (ManualRechargeDO manualRechargeDO : list) {
                            if (manualRechargeDO.getTargetDate().equals(item.get("target_date").toString()) || manualRechargeDO.getTargetDate().before((Date) item.get("target_date"))) {
                                item.put("active", Integer.parseInt(item.get("active").toString()) + manualRechargeDO.getAmount());
                                break;
                            }
                        }
                    });
                }

            }
        } catch (Exception e){ log.error(String.valueOf(e)); }

        result.forEach(item->{
            for(int i=0; i<ret.size(); i++){
                if(item.get("target_date").toString().equals(ret.get(i).get("target_date").toString())){
                    ret.get(i).put("active", item.getOrDefault("active", 0));
                }
            }
        });
        return ret;
    }

    public List<Map> cardActiveList(PropQueryDTO query) {
        Date current_date = new Date();
        String activeDate = TimeUtils.addDay(current_date, -30, "yyyy-MM-dd");
        query.setActiveDate(activeDate);
        List<Map> result = cardPropDOMapper.activeList(query);
        List<Map> ret = generate_30_days(current_date, "active");
        result.forEach(item->{
            for(int i=0; i<ret.size(); i++){
                if(item.get("target_date").toString().equals(ret.get(i).get("target_date").toString())){
                    ret.get(i).put("active", item.getOrDefault("active", 0));
                }
            }
        });
        return ret;
    }

    public List<Map> ticketActiveList(PropQueryDTO query) {
        Date current_date = new Date();
        String activeDate = TimeUtils.addDay(current_date, -30, "yyyy-MM-dd");
        query.setActiveDate(activeDate);
        List<Map> result = ticketPropDOMapper.activeList(query);
        List<Map> ret = generate_30_days(current_date, "active");
        result.forEach(item->{
            for(int i=0; i<ret.size(); i++){
                if(item.get("target_date").toString().equals(ret.get(i).get("target_date").toString())){
                    ret.get(i).put("active", item.getOrDefault("active", 0));
                }
            }
        });
        return ret;
    }

    public List<Map> scoreActiveList(PropQueryDTO query) {
        Date current_date = new Date();
        String activeDate = TimeUtils.addDay(current_date, -30, "yyyy-MM-dd");
        query.setActiveDate(activeDate);
        List<Map> result = scorePropDOMapper.activeList(query);
        List<Map> ret = generate_30_days(current_date, "active");
        result.forEach(item->{
            for(int i=0; i<ret.size(); i++){
                if(item.get("target_date").toString().equals(ret.get(i).get("target_date").toString())){
                    ret.get(i).put("active", item.getOrDefault("active", 0));
                }
            }
        });
        return ret;
    }

    public List<Map> voiceCardActiveList(PropQueryDTO query) {
        Date current_date = new Date();
        String activeDate = TimeUtils.addDay(current_date, -30, "yyyy-MM-dd");
        query.setActiveDate(activeDate);
        List<Map> result = voiceCardPropDOMapper.activeList(query);
        List<Map> ret = generate_30_days(current_date, "active");
        result.forEach(item->{
            for(int i=0; i<ret.size(); i++){
                if(item.get("target_date").toString().equals(ret.get(i).get("target_date").toString())){
                    ret.get(i).put("active", item.getOrDefault("active", 0));
                }
            }
        });
        return ret;
    }

    @Autowired
    private ActivityDOMapper activityDOMapper;

    public List<Map> luckyCardList(ActivityDO query) {
        query.setDrawType(3);
        List<Map> ret = new ArrayList<>();
        List<Map> intraDayUsers = activityDOMapper.intraDayUser(query);
        // 活跃人数列表
        PropQueryDTO param = new PropQueryDTO();
        if (query.getChannels() != null ){
            param.setChannels(query.getChannels());
        }
        param.setLimit(query.getLimit());
        param.setOffset(query.getOffset());
        param.setAbTest(query.getAbTest());
        param.setBundleId(query.getBundleId());
        List<DiamondPropDO> active = diamondPropDOMapper.listActive(param);
        // 当前奖池
        List<ActivityDO> currentList = activityDOMapper.listCurPool(query);
        // 消耗钻石
        query.setTarget("cost_num");
        query.setCostType(2);
        List<Map> diamondList = activityDOMapper.listSum(query);
        // 消耗副卡
        query.setCostType(1);
        List<Map> luckyList = activityDOMapper.listSum(query);
        // 单抽次数
        query.setCostNum(1);
        List<Map> cardOnesList = activityDOMapper.count(query);  // 福卡单抽
        query.setCostType(2);
        query.setCostNum(10);
        List<Map> diamondOnesList = activityDOMapper.count(query);
        // 十连抽
        query.setCostNum(95);
        List<Map> diamondTensList = activityDOMapper.count(query);
        // 百连抽
        query.setCostNum(900);
        List<Map> diamondHundredList = activityDOMapper.count(query);
        // 总注入钻石
        query.setCostNum(null);
        query.setCostType(null);
        query.setTarget("inject_pool");
        List<Map> injectList = activityDOMapper.listSum(query);
        // 返奖
        query.setTarget("award_diamond");
        List<Map> awardList = activityDOMapper.listSum(query);
        // 总参与人数
        List<ActivityDO> totalList = activityDOMapper.totalUser(query);

        for(int i=0; i<intraDayUsers.size(); i++){
            Map tmp = new HashMap();
            String target_date = intraDayUsers.get(i).get("target_date").toString();
            Date date = null;
            try {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
                date = simpleDateFormat.parse(target_date);
            } catch (Exception e){}
            tmp.put("date", target_date);
//            tmp.put("active", intraDayUsers.get(i).get("count"));
            for(DiamondPropDO ob: active) {
                if(ob.getTargetDate() != null && ob.getTargetDate().toString().equals(date.toString())) {
                    tmp.put("active", active.get(i).getActiveCount());
                }
            }

            for(ActivityDO ob: currentList) {
                if(ob.getTargetDate() != null && ob.getTargetDate().toString().equals(date.toString())) {
                    tmp.put("currentPool", ob.getCurrentPool());
                }
            }
            for(Map ob: diamondList) {
                if(ob.get("target_date") != null && ob.get("target_date").toString().equals(target_date)) {
                    tmp.put("consumeDiamond", ob.get("cost_num"));
                }
            }
            for(Map ob: luckyList) {
                if(ob.get("target_date") != null && ob.get("target_date").toString().equals(target_date)) {
                    tmp.put("consumeCard", ob.get("cost_num"));
                }
            }
            int cardOne = 0;
            int diamondOne = 0;  // 福卡单抽
            for(Map ob: cardOnesList) {
                if(ob.get("target_date") != null && ob.get("target_date").toString().equals(target_date)) {
                    cardOne = Integer.parseInt(ob.get("count").toString());
                }
            }
            for(Map ob: diamondOnesList) {
                if(ob.get("target_date") != null && ob.get("target_date").toString().equals(target_date)) {
                    diamondOne = Integer.parseInt(ob.get("count").toString());
                }
            }
            tmp.put("ones", (cardOne + diamondOne));

            for(Map ob: diamondTensList) {
                if(ob.get("target_date") != null && ob.get("target_date").toString().equals(target_date)) {
                    tmp.put("tens", ob.get("count"));
                }
            }
            for(Map ob: diamondHundredList) {
                if(ob.get("target_date") != null && ob.get("target_date").toString().equals(target_date)) {
                    tmp.put("hundred", ob.get("count"));
                }
            }
            for(Map ob: injectList) {
                if(ob.get("target_date") != null && ob.get("target_date").toString().equals(target_date)) {
                    tmp.put("inject", ob.get("inject_pool"));
                }
            }
            for(Map ob: awardList) {
                if(ob.get("target_date") != null && ob.get("target_date").toString().equals(target_date)) {
                    tmp.put("award", ob.get("award_diamond"));
                }
            }
            for(ActivityDO ob: totalList) {
                if(ob.getTargetDate() != null && ob.getTargetDate().toString().equals(date.toString())) {
                    tmp.put("totalUser", ob.getTotalUserLuck());
                }
            }
            ret.add(tmp);
        }
        return ret;
    }

    public List<Map> luckyCardPoolList(ActivityDO query) {
        Date current_date = new Date();
        query.setLimit(30);
        query.setDrawType(3);
        List<ActivityDO> result = activityDOMapper.listCurPool(query);
        List<Map> ret = generate_30_days(current_date, "pool");
        result.forEach(item->{
            for(int i=0; i<ret.size(); i++){
                String target_date = ret.get(i).get("target_date").toString();
                Date date = null;
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
                    date = simpleDateFormat.parse(target_date);
                } catch (Exception e){e.printStackTrace();}
                if(item.getTargetDate().toString().equals(date.toString())){
                    ret.get(i).put("pool", item.getCurrentPool() != null ? item.getCurrentPool():0);
                }
            }
        });
        return ret;
    }

    public List<Map> luckyGiftList(ActivityDO query) {
        query.setDrawType(4);
        List<Map> ret = new ArrayList<>();
        List<Map> intraDayUsers = activityDOMapper.intraDayUser(query);
        // 活跃人数列表
        PropQueryDTO param = new PropQueryDTO();
        if (query.getChannels() != null ){
            param.setChannels(query.getChannels());
        }
        param.setLimit(query.getLimit());
        param.setOffset(query.getOffset());
        param.setAbTest(query.getAbTest());
        param.setBundleId(query.getBundleId());
        List<DiamondPropDO> active = diamondPropDOMapper.listActive(param);
        // 当前奖池
        List<ActivityDO> currentList = activityDOMapper.listCurPool(query);
//        // 消耗钻石
//        query.setTarget("inject_pool");
//        List<ActivityDO> diamondList = activityDOMapper.listSum(query);
        // fudai
        query.setTarget("cost_num");
        query.setCostType(48);
        List<Map> bagList = activityDOMapper.listSum(query);
        // cat
        query.setCostType(49);
        List<Map> catList = activityDOMapper.listSum(query);
        // tree
        query.setCostType(50);
        List<Map> treeList = activityDOMapper.listSum(query);
        // frog
        query.setCostType(51);
        List<Map> frogList = activityDOMapper.listSum(query);
        // 总注入钻石
        query.setCostNum(null);
        query.setCostType(null);
        query.setTarget("inject_pool");
        List<Map> injectList = activityDOMapper.listSum(query);
        // 返奖
        query.setTarget("award_diamond");
        List<Map> awardList = activityDOMapper.listSum(query);
        // 总参与人数
        List<ActivityDO> totalList = activityDOMapper.totalUser(query);

        for(int i=0; i<intraDayUsers.size(); i++){
            Map tmp = new HashMap();
            String target_date = intraDayUsers.get(i).get("target_date").toString();
            Date date = null;
            try {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
                date = simpleDateFormat.parse(target_date);
            } catch (Exception e){}
            tmp.put("date", target_date);
//            tmp.put("active", intraDayUsers.get(i).get("count"));
            for(DiamondPropDO ob: active) {
                if(ob.getTargetDate() != null && ob.getTargetDate().toString().equals(date.toString())) {
                    tmp.put("active", active.get(i).getActiveCount());
                }
            }

            for(ActivityDO ob: currentList) {
                if(ob.getTargetDate() != null && ob.getTargetDate().toString().equals(date.toString())) {
                    tmp.put("currentPool", ob.getCurrentPool());
                }
            }

            for(Map ob: bagList) {
                if(ob.get("target_date") != null && ob.get("target_date").toString().equals(target_date)) {
                    tmp.put("consumeBag", ob.get("cost_num"));
                }
            }

            for(Map ob: catList) {
                if(ob.get("target_date") != null && ob.get("target_date").toString().equals(target_date)) {
                    tmp.put("cat", ob.get("cost_num"));
                }
            }
            for(Map ob: treeList) {
                if(ob.get("target_date") != null && ob.get("target_date").toString().equals(target_date)) {
                    tmp.put("tree", ob.get("cost_num"));
                }
            }
            for(Map ob: frogList) {
                if(ob.get("target_date") != null && ob.get("target_date").toString().equals(target_date)) {
                    tmp.put("frog", ob.get("cost_num"));
                }
            }

            for(Map ob: injectList) {
                if(ob.get("target_date") != null && ob.get("target_date").toString().equals(target_date)) {
                    tmp.put("inject", ob.get("inject_pool"));
                }
            }
            for(Map ob: awardList) {
                if(ob.get("target_date") != null && ob.get("target_date").toString().equals(target_date)) {
                    tmp.put("award", ob.get("award_diamond"));
                }
            }
            for(ActivityDO ob: totalList) {
                if(ob.getTargetDate() != null && ob.getTargetDate().toString().equals(date.toString())) {
                    tmp.put("totalUser", ob.getTotalUser());
                }
            }
            ret.add(tmp);
        }

        return ret;
    }

    public List<Map> luckyGiftPoolList(ActivityDO query) {
        Date current_date = new Date();
        query.setLimit(30);
        query.setDrawType(4);
        List<ActivityDO> result = activityDOMapper.listCurPool(query);
        List<Map> ret = generate_30_days(current_date, "pool");
        result.forEach(item->{
            for(int i=0; i<ret.size(); i++){
                String target_date = ret.get(i).get("target_date").toString();
                Date date = null;
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
                    date = simpleDateFormat.parse(target_date);
                } catch (Exception e){e.printStackTrace();}
                if(item.getTargetDate().toString().equals(date.toString())){
                    ret.get(i).put("pool", item.getCurrentPool() != null ? item.getCurrentPool():0);
                }
            }
        });
        return ret;
    }

    public List<Map> generate_30_days(Date date, String key) {
        List<Map> result = new ArrayList<>();
        for(int i=-30; i<=0; i++){
            Map tmpMap = new HashMap();
//            System.out.println(i);
            try{
                String targetDate = TimeUtils.addDay(date, i, "yyyy-MM-dd");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Long targetTimestamp = simpleDateFormat.parse(targetDate).getTime();
                Date tmpDate = new java.sql.Date(targetTimestamp);
//                tmpMap.put("target_date", targetTimestamp);
                tmpMap.put("target_date", tmpDate);
                tmpMap.put(key, "-");
            } catch (Exception e){
                System.out.println(e.toString());
            }
            result.add(tmpMap);
        }
        return result;
    }

    public void UserClassEdit(JSONObject params){
        UserClassifyDO query = new UserClassifyDO();
        query.setType(params.getString("type"));
        List<String> ids = Arrays.asList(params.getString("userIds").split(","));
        query.setUserIds(ids);
        // 先删除分类用户 在写入分类用户
        userClassifyDOMapper.delete(query);
        userClassifyDOMapper.insert(query);
    }

    public JSONObject getIpAddress(Map<String, String> queryMap){
        String url= "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php";
        String local = ipAddressMap.getOrDefault(queryMap.getOrDefault("userId", null), null);
        if (local == null && queryMap.getOrDefault("query", null) != null){
            String body= HttpInvokeUtil.httpGet(url, queryMap, null);
            JSONObject bodyObject = JSONObject.parseObject(body);
            JSONArray dataList = bodyObject.getJSONArray("data");
            JSONObject localObject = dataList.getJSONObject(0);
            JSONObject response = new JSONObject();
            response.put("local", localObject.getString("location"));
            ipAddressMap.put(queryMap.getOrDefault("userId", null), localObject.getString("location"));
            return response;
        }else {
            JSONObject response = new JSONObject();
            response.put("local", local);
            return response;
        }
    }

    public void deleteUserClass(JSONObject params){
        UserClassifyDO query = new UserClassifyDO();
        query.setType(params.getString("type"));
        userClassifyDOMapper.delete(query);
    }

    public List<UserClassifyDO> userClassList(){
        return userClassifyDOMapper.typeList();
    }

    // 2023-04-17 tarot
    public int getRegisterStatisticsCount(String appName, String appChannel, String appVersion, String startTime, String endTime) {
        return accountRegisterStatisticsMapper.totalCount(appName, appChannel, appVersion, startTime, endTime);
    }

    public List<AccountRegisterStatistics> getRegisterStatistics(int offset, int pageSize, String appName, String appChannel, String appVersion, String startTime, String endTime,
                                   String orderBy, String orderType) {
        List<AccountRegisterStatistics> list = accountRegisterStatisticsMapper.selectAll(offset, pageSize, appName, appChannel, appVersion, startTime, endTime);
        return list;
    }

    // 2023-07-13 tarot
    public int getMarketStatisticsCount() {
        return marketStatisticsMapper.totalCount();
    }

    public List<MarketStatistics> getMarketStatistics(int offset, int pageSize) {
        List<MarketStatistics> list = marketStatisticsMapper.selectAll(offset, pageSize);
        return list;
    }

    public void updateMarketExtra(MarketExtraDTO updateDTO) {
        MarketStatisticsExample sample = new MarketStatisticsExample();
        sample.createCriteria().andIdEqualTo(updateDTO.getId());
        MarketStatistics record = new MarketStatistics();
        record.setAdRevenue(updateDTO.getAdRevenue());
        record.setDeliveryCost(updateDTO.getDeliveryCost());
        marketStatisticsMapper.updateByExampleSelective(record, sample);
    }

    public JSONObject getQuickBiTicketData() {
        String url = "https://bi.aliyun.com/openapi/ac3rd/ticket/create?worksId=1a351ae5-bea5-4009-b8f2-0ce156f9356f&aliyunUid=1789706193081844&accessKey=482a572d-3389-4d24-8fa9-2c927f30a037&accessId=c5a602b2-db25-4a8b-b370-d4723ab9ea12&validityTime=240";
        String response = HttpInvokeUtil.httpGet(url, null, null);
        JSONObject jsonObject = JSONObject.parseObject(response);
        return jsonObject.getJSONObject("data");
    }

    // 2023-09-20 tarot
    public int getAdvisorSummaryStatisticsCount() {
        return advisorSummaryDataMapper.totalCount();
    }

    public List<AdvisorSummaryData> getAdvisorSummaryStatistics(int offset, int pageSize) {
        List<AdvisorSummaryData> list = advisorSummaryDataMapper.selectAll(offset, pageSize);
        return list;
    }

    public long getOrderSummaryStatisticsCount(List<Integer> types) {
        final OrderSummaryDataExample example = new OrderSummaryDataExample();
        example.createCriteria().andOrderTypeIn(types);
        return orderSummaryDataMapper.countByExample(example);
    }

    public List<OrderSummaryData> getOrderSummaryStatistics(List<Integer> types, int offset, int pageSize) {
        final OrderSummaryDataExample example = new OrderSummaryDataExample();
        example.setOrderByClause("target_date desc limit " + offset + "," + pageSize);
        example.createCriteria().andOrderTypeIn(types);
        return orderSummaryDataMapper.selectByExample(example);
    }
}
